package team.bluepen.order.web.servlet;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import team.bluepen.order.ErrorPack;
import team.bluepen.order.constant.Constant;
import team.bluepen.order.constant.ErrorCode;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Kai
 */
public abstract class BaseServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.sendError(401);
    }

    @Override
    protected final void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        if (!checkLogin(req) && isCheckLogin()) {
            setJsonHeader(resp);
            writeJson(resp, new ErrorPack(ErrorCode.ERROR_USER_NOT_LOGIN,
                    "user not login").toCodePack());
            return;
        }
        post(req, resp);
    }

    protected boolean isCheckLogin() {
        return true;
    }


    protected abstract void post(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException;

    private boolean checkLogin(HttpServletRequest req) {
        HttpSession session = req.getSession();
        return session.getAttribute(Constant.SESSION_USER) != null;
    }

    protected void setJsonHeader(HttpServletResponse resp) {
        resp.setContentType("application/json; charset=UTF-8");
    }

    protected void writeJson(HttpServletResponse resp, Object obj) throws IOException {
        PrintWriter writer = resp.getWriter();
        Gson gson = new GsonBuilder().create();
        writer.print(gson.toJson(obj));
    }
}
